/**
 * Created with  SublimeText
 * @Author:      Lyle
 * @DateTime:    2017-03-13 10:59:00
 * @Description: 
 */
import axios from 'axios'
import qs from 'qs'

//API global control
axios.defaults.baseURL = 'http://127.0.0.1:8080/api';
axios.defaults.timeout = 60000;
axios.defaults.withCredentials = true; //firefox
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.transformRequest = [function(data) {
    //console.log(qs.stringify(data)); 
    //return a string or an instance of Buffer, ArrayBuffer,FormData or Stream
    return qs.stringify(data);
}];

// Add a request interceptor
axios.interceptors.request.use(function(config) {
    return config;
}, function(error) {
    return Promise.reject(error);
});

// Add a response interceptor
axios.interceptors.response.use(function(response) {
    return response;
}, function(error) {
    return Promise.reject(error);
});

//axios 
function requestEntrance(data, callback) {
    if (typeof(callback) === 'object') {
        callback.success = callback.success || function() {};
        callback.error = callback.error || function() {};
        callback.complete = callback.complete || function() {};
        axios(data)
            .then(function(response) {
                if (response) {
                    callback.complete();
                    callback.success(response.data);
                }
            })
            .catch(function(error) {
                callback.complete();
                callback.error(error);
                // alert('Oops! There was a problem connecting to the network. Please refresh!')
                console.log('error:', data.url, error);
            });
    }
}

/****************************** api **************************/
//API test
export function test(obj) {
    let requestData = {
            method: 'get',
            url: 'test.php',
        },
        requestCallback = {};
    requestCallback.success = function(response) {
        obj.success ? obj.success(response) : '';
    };

    requestEntrance(requestData, requestCallback);
}

//API asynctest
export function asynctest(obj) {
    let requestData = {
            method: 'get',
            //url: 'http://127.0.0.1:8080/data',
            url: 'test.php',
        },
        requestCallback = {};

    requestCallback.success = function(response) {
        obj.success ? obj.success(response) : '';
    };

    requestEntrance(requestData, requestCallback);
}